#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include <assert.h>
#include "detectwr.c"
#define ERR_EXIT(m) \
    do { \
        perror(m); \
        exit(EXIT_FAILURE); \
    } while (0)




int main(void)
{
    int sock;
    if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
        //  listenfd = socket(AF_INET, SOCK_STREAM, 0)
        ERR_EXIT("socket error");


    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(5188);
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    /* inet_aton("127.0.0.1", &servaddr.sin_addr); */

    if (connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
        ERR_EXIT("connect error");

    int retval;
    int nread, nwrite;
    int ntotal = 0;
    #define LEN_BUF 1024
    char buf[LEN_BUF];

    int idx = 0;
    struct timeval tv;

    while(1) {
        snprintf(buf, LEN_BUF, "%06d", idx);
        idx ++;

        tv.tv_sec = 0;
        tv.tv_usec = 0;
        retval = udetect_write(sock, &tv);

        if(retval == 0) {
            printf("server writeable.\n");
            nwrite = write(sock, buf, 1);
            assert(nwrite > 0);
            ntotal += nwrite;
            printf("write finished.(%d).\n", ntotal);

            continue;
            nread = read(sock, buf, LEN_BUF);
            assert(nread == nwrite);
            printf("got echo.\n");
        }
        else {
            printf("server not writeable.\n");
        }

        sleep(2);
    }

    close(sock);

    return 0;
}
